const router = require('koa-router')()

const { ErrorRes, SuccessRes } = require('../res-model/index')
const { userNoExistFailInfo } = require('../res-model/failInfo/index')

const { phoneNumberSchema, phoneNumberVeriCodeSchema, userInfoSchema } = require('../validator/users')

const sendVeriCode = require('../controller/users/sendVeriCode')
const loginByPhoneNumber = require('../controller/users/loginByPhoneNumber')
const updateUserInfo = require('../controller/users/updateUserInfo')

const { findOneUser } = require('../service/users')

const genValidator = require('../middleware/genValidator')

router.prefix('/api/users')

// 生成短信验证码
router.post('/genVeriCode', genValidator(phoneNumberSchema), async ctx => {
  const { phoneNumber, isRemoteTest } = ctx.request.body
  const res = await sendVeriCode(phoneNumber, isRemoteTest)
  ctx.body = res
})

// 使用手机号登录
router.post('/loginByPhoneNumber', genValidator(phoneNumberVeriCodeSchema), async ctx => {
  const { phoneNumber, veriCode } = ctx.request.body
  const res = await loginByPhoneNumber(phoneNumber, veriCode)
  ctx.body = res
})

// 获取用户信息
router.get('/getUserInfo', async ctx => {
  const res = await findOneUser({ username: ctx.state.user.username })
  if (res) {
    ctx.body = new SuccessRes(res)
  } else {
    ctx.body = new ErrorRes(userNoExistFailInfo)
  }
})

// 修改用户信息
router.patch('/updateUserInfo', genValidator(userInfoSchema), async ctx => {
  const res = await updateUserInfo(ctx.state.user, ctx.request.body)
  ctx.body = res
})

module.exports = router
